import json

from django.http import Http404
from rest_framework.exceptions import APIException
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from API.utils.auth import jwtQueryParamsBaseAuthentication

from API.utils.jwt_token import create_token
from API.utils.openID import getOpenID

# 导入模型
from API.models import University, Question, ImageForQuestion, Answer, Slideshow, ImageForAnswer, BindUserAndQuestionTag
from API.models import Professional
from API.models import WeChatUser
from API.models import TagToUser,TagToQuestion
from API.models import InviteRelationship
from API.models import ReplyRelationship

# 导入序列化器
from API.serializers import UniversityModelSerializer, ImageForQuestionCreateModelSerializer, \
    SearchQuestionModelSerializer
from API.serializers import QuestionModelSerializer
from API.serializers import AnswerCreateModelSerializer
from API.serializers import SlideshowModelSerializer
from API.serializers import FeedbackModelSerializer
from API.serializers import WeChatUserModelSerializer, WeChatUserBriefModelSerializer
from API.serializers import ImageForQuestionModelSerializer,ImageForAnswerModelSerializer
from API.serializers import TagToQuestionModelSerializer,TagToUserModelSerializer
from API.serializers import QuestionModelCreateSerializer
from API.serializers import AnswerModelSerializer
from API.serializers import WeChatUserInfoModelSerializer
from API.serializers import InviteRelationshipModelSerializer
from API.serializers import InviteRelationshipListModelSerializer
from API.serializers import ReplyRelationshipListModelSerializer
from API.serializers import ReplyRelationshipModelSerializer


# Create your views here.
class UniversityModelAPIView(APIView):
    """获取高校专业信息"""

    def get_object(self):
        try:
            return University.objects.all()
        except:
            return None

    def get(self,request):
        universitys = self.get_object()
        if universitys:
            serializer = UniversityModelSerializer(instance=universitys, many=True)
        else:
            return Response({
                'status':210,
                'msg': '校方资源未就绪.',
            })
        return Response({
            'status':200,
            'msg': 'ok',
            'schoolInfo':serializer.data
        })

    def post(self,request):
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }

        if not 'searchInfo' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = "searchInfo资源未获得"
            return Response(ret_data)

        searchInfo = request.data['searchInfo']
        school_list = University.objects.filter(name__regex=searchInfo)
        print(school_list)
        if not school_list:
            ret_data['status'] = 210
            ret_data['msg'] = '很抱歉我们没能提供贵校的信息'
            return Response(ret_data)

        serializer = UniversityModelSerializer(instance=school_list,many=True)
        print(serializer.data)
        ret_data['schoolInfo'] = serializer.data
        return Response(ret_data)


class infection(APIView):

    def get(self,request):

        filepath =r'C:\Users\16931\Desktop\小程序2.0\wxAppBackend-new\backend\API\utils\newdata.json'
        with open(file=filepath,mode='r', encoding='utf-8') as readStream:
           shoolInfo =  json.load(readStream)

        for school in list(shoolInfo.items()):
            prolist = []
            for key,value in school[1].items():
                prolist.extend(value)

            newprofList = []
            for item in prolist:
                d = {}
                d['name'] = item
                newprofList.append(d)

            data = {
                'name': school[0],
                'professionals': newprofList
            }

            # # 1. 新建大学记录
            university = University.objects.get_or_create(name=data['name'])[0]
            # 2. 获取该大学所设专业,并遍历获取记录
            professionals = data['professionals']
            professionals_obj_list = []
            for one in professionals:
                major = Professional.objects.get_or_create(name=one['name'])[0]
                professionals_obj_list.append(major)

                #     # 3.所有专业与该大学关联
                university.professionals.add(major)
            print(professionals_obj_list)

        return Response(1)


class LoginModelAPIView(APIView):
    """用户登录视图"""

    def get(self,request):
        """
        :param request: code
        :return:
        """
        ret_data = {
            'status': 200,
            'msg':'ok'
        }
        # 判断前台是否传来用户的code,如果没有,返回错误信息
        if "code" not in request.query_params:
            ret_data['status'] = 204
            ret_data['msg'] = 'code资源未获得'
            return Response(ret_data)

        # 获取code
        code = request.query_params['code']

        # 通过code 提取用户的openID
        openID = getOpenID(code=code)

        # 判断是否获得正确返回值, 如果没有值,返回错误信息
        if openID is None:
            ret_data['status'] = '203'
            ret_data['msg'] = '错误code资源'
            return Response(ret_data)

        user = WeChatUser.objects.filter(openID=openID).first()

        # 判断是否存在以该openID为基的用户, 如果不存在,向前台请求注册
        if not user:
            ret_data['status'] = 210
            ret_data['msg'] = '资源未就位! 用户未注册,请跳转至引导页'
            return Response(ret_data)

        user_serializer = WeChatUserInfoModelSerializer(instance=user)

        # 获取用户的问题
        user_questions = Question.objects.filter(we_chat_user=user)
        question_serializer = QuestionModelSerializer(instance=user_questions, many=True)

        # 获取用户的问题
        user_answer = Answer.objects.filter(we_chat_user=user, parent=None)
        answer_serializer = AnswerModelSerializer(instance=user_answer, many=True)

        ret_data['user'] = user_serializer.data
        ret_data['question_list'] = question_serializer.data
        ret_data['answer_list'] = answer_serializer.data
        ret_data['token'] = create_token({"openID": user.openID, "nickName": user.nickName})
        ret_data['msg'] = '登录成功'
        print(ret_data['token'])
        return Response(ret_data)

    def post(self,request):
        ret_data = {
            'status':200,
            'msg':'ok'
        }

        # 判断前台资源是否传来,如果没有,函数结束,返回错误信息
        if  'userInfo' not in request.data or 'uid' not in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = '信息资源未获得'
            return Response(ret_data)

        # 获取前台资源: uid 用户id, userInfo 微信基本信息
        uid = request.data['uid']
        userInfo = request.data['userInfo']

        # 判断用户信息是否更换,如果是, 更新数据
        user = WeChatUser.objects.get(id=uid)
        if user.nickName != userInfo['nickName']:
            user.nickName = userInfo['nickName']
        if user.avatarUrl != userInfo['avatarUrl']:
            user.avatarUrl = userInfo['avatarUrl']
        if user.gender != userInfo['gender']:
            user.gender = userInfo['gender']
        # 数据保存
        user.save()

        serializer = WeChatUserInfoModelSerializer(instance=user)

        # 返回信息
        # 获取用户的问题
        user_questions = Question.objects.filter(we_chat_user=user)
        question_serializer = QuestionModelSerializer(instance=user_questions, many=True)

        # 获取用户的问题
        user_answer = Answer.objects.filter(we_chat_user=user)
        answer_serializer = AnswerModelSerializer(instance=user_answer, many=True)

        ret_data['we_chat_user'] = serializer.data
        ret_data['question_list'] = question_serializer.data
        ret_data['answer_list'] = answer_serializer.data
        ret_data['token'] = create_token({"openID":user.openID,"nickName":user.nickName})
        return Response(ret_data)


class RegisterModelAPIView(APIView):
    """新用户注册视图"""

    def post(self,request):
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }

        # 判断前台是否传来注册资源:openID和userInfo, 如果未传递,函数结束,返回错误信息
        if  'userInfo' not in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = '未获得注册资源,请重试!'
            return Response(ret_data)

        # 获取注册资源
        userInfo = request.data['userInfo']

        # 换取openID, 资源切换
        openID = getOpenID(userInfo['code'])
        userInfo['openID'] = openID
        del userInfo['code']
        # print(userInfo)

        # 判断用户是否已注册, 如果已注册, 函数结束,返回错误信息
        if WeChatUser.objects.filter(openID=userInfo['openID']):
            ret_data['status'] = 203
            ret_data['msg'] = '用户已注册,请勿重新注册!'
            return Response(ret_data)

        # 未注册, 则将注册资源反序列化
        serializer = WeChatUserModelSerializer(data=userInfo)

        # 校验反序列化数据有效性, 如有效则入库,并结束函数,返回有效信息
        if serializer.is_valid():

            # 此处保存,因为存在外键,需要获取外键的对象,然后传递到反序列化的数据中,然后再保存
            serializer.validated_data['university'] = University.objects.get(id=userInfo['university'])
            serializer.validated_data['professional'] = Professional.objects.get(id=userInfo['professional'])
            # print(serializer.validated_data)
            user = serializer.save()
            print(user)
            userinfo_serializer = WeChatUserInfoModelSerializer(instance=user)
            ret_data['we_chat_user'] = userinfo_serializer.data

            ret_data['question_list'] = []
            ret_data['answer_list'] = []

            ret_data['token'] = create_token({"openID":serializer.data['openID'],"nickName":serializer.data['nickName']})
            return Response(ret_data)
        else:
            # 如果校验不成功,结束函数,返回错误信息
            print(serializer.errors)
            ret_data['status'] = 203
            ret_data['msg'] = "注册失败,无效的用户资源"
            return Response(ret_data)


class ImageModelAPIView(APIView):
    """图片上传视图"""

    authentication_classes = [jwtQueryParamsBaseAuthentication]

    def post(self,request):
        ret_data = {
            'status':200,
            'msg':'ok'
        }
        # 判断前台是否传来信息资源, 如果没有, 函数结束, 返回错误信息
        if not 'image' in request.data or not 'imageClassify' in request.data or not 'id' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = '图片资源或者区分信息未传递,请重试!'
            return Response(ret_data)
        # 获取信息资源
        print(request.data)
        image_resource = request.data['image']

        # 通过classify判断上传资源分类,0为问题,1为回复
        classify = int(request.data['imageClassify'])
        id = int(request.data['id'])
        resource = {}
        if classify == 0:
            resource = {
                'question':id,
                'image': image_resource
            }
        elif classify == 1:
            resource = {
                'answer': id,
                'image': image_resource
            }
        if resource == None:
            ret_data['status'] = 204
            ret_data['msg'] = '图片资源或者区分信息未传递,请重试!'
            return Response(ret_data)

        try:
            id = self.preserve(resource=resource,classify=classify)
        except APIException as e:
            ret_data['status'] = e.get_codes()
            ret_data['msg'] = e.get_full_details()
            return Response(ret_data)

        ret_data['savedImageId'] = id
        return Response(ret_data)

    def preserve(self,resource,classify):
        # 反序列化
        print(resource)
        if classify == 0:
            serializer = ImageForQuestionCreateModelSerializer(data=resource)
        elif classify == 1:
            serializer =ImageForAnswerModelSerializer(data=resource)
        else:
            raise APIException(detail='classify 无效',code=204)
        # 数据校验
        if serializer.is_valid():
            # 数据保存
            image = serializer.save()
            # 返回id ,用于之后关联问题
            return image.id
        else:
            # 表明验证失效,返回空
            print(serializer.errors)
            return None


class TagModelAPIView(APIView):
    """问题/用户标签搜索/删除接口"""

    authentication_classes = [jwtQueryParamsBaseAuthentication]

    def get(self,request):
        ret_data = {
            'status':200,
            'msg':'ok'
        }
        # 判断前台是否传递信息资源, 如果没有,返回错误信息
        if not 'tag_str' in request.query_params or not 'tagClassify' in request.query_params:
            ret_data['status'] = 204
            ret_data['msg'] = '标签资源或区分资源未传递,请重试'
            return Response(ret_data)

        # 获取资源
        tag_resource = request.query_params['tag_str']
        tag_classify = int(request.query_params['tagClassify'][0])
        # 获取标签
        try:
            tag = self.search(resource=tag_resource,classify=tag_classify)
        except APIException as e:
            ret_data['status'] = e.get_codes()
            ret_data['msg'] = e.get_full_details()
            return Response(ret_data)
        #
        ret_data['tag_list'] = tag
        return Response(ret_data)

    def post(self,request):
        """用于个性标签与用户关联"""

        ret_data = {
            'status' :200,
            'msg':'ok'
        }

        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])

        # 判断前台是否有信息资源传来, 如果没有,返回错误信息
        if not 'tags' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = 'tags信息资源传未传递'
            return Response(ret_data)

        # 获取信息资源
        tags = request.data['tags']
        for item in tags:
            # 确定是否存在正确的标签
            if not TagToUser.objects.filter(id=item['id'],text=item['text']):
                ret_data['status'] = 203
                ret_data['msg'] = '不是正确的标签,请勿违规操作'
                return Response(ret_data)
            tag = TagToUser.objects.get(id=item['id'],text=item['text'])

            user.tag.add(tag)
        serializer = WeChatUserInfoModelSerializer(instance=user)
        ret_data['we_chat_user'] = serializer.data
        return Response(ret_data)

    def delete(self,request):
        """用户与标签之间解除关联"""
        ret_data = {
            'status':200,
            'msg':'ok'
        }

        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])

        # 判断前台是否有信息资源传来, 如果没有,返回错误信息
        if not 'tag' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = 'tag信息资源传未传递'
            return Response(ret_data)

        tag = request.data['tag']
        print(tag)
        # 确定是否存在正确的标签
        if not TagToUser.objects.filter(id=tag['id'],text=tag['text']):
            ret_data['status'] = 203
            ret_data['msg'] = '不是正确的标签,请勿违规操作'
            return Response(ret_data)
        tag = TagToUser.objects.get(id=tag['id'],text=tag['text'])

        # 解除用户与标签的关联
        user.tag.remove(tag)
        print(user.tag)
        serializer = WeChatUserInfoModelSerializer(instance=user)
        ret_data['we_chat_user'] = serializer.data
        return Response(ret_data)

    def search(self,resource, classify):
        """聚合搜索函数, 用classify函数区分究竟是哪个类的标签,classify作为要搜索的标签文本
            如果存在标签,则直接返回其序列化后的3*data, 后续可加上返回相关的标签
            如果不存在标签, 先创建再返回.
        """
        if classify == 0:
            tags = TagToUser.objects.filter(text__regex=resource)
            if not tags:
                tags = TagToUser.objects.get_or_create(text=resource)[0]
                serializer = TagToUserModelSerializer(instance=tags)
            else:
                serializer = TagToUserModelSerializer(instance=tags,many=True)
            # print(serializer.data)
            return serializer.data
        elif classify == 1:
            # 问题标签
            tags = TagToQuestion.objects.filter(text__regex=resource.strip())
            print(tags)
            if not tags:
                tags = TagToQuestion.objects.get_or_create(text=resource)[0]
                print(tags)
                serializer = TagToQuestionModelSerializer(instance=tags)
                print(serializer.data)
            else:
                serializer = TagToQuestionModelSerializer(instance=tags,many=True)
            # print(serializer.data)
            return serializer.data
        else:
            raise APIException(detail='classify 无效',code=204)


class TagsModelAPIView(APIView):
    """问题/用户标签集视图"""

    authentication_classes = [jwtQueryParamsBaseAuthentication]

    def get(self,request):
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 判断前台是否传递信息资源, 如果没有,返回错误信息
        if not 'tagClassify' in request.query_params:
            ret_data['status'] = 204
            ret_data['msg'] = '标签区分资源未传递,请重试'
            return Response(ret_data)

        # 获取资源
        tag_classify = int(request.query_params['tagClassify'][0])

        # 获取序列化数据
        try:
            tag_list = self.all(classify=tag_classify)
        except APIException as e:
            ret_data['status'] = e.get_codes()
            ret_data['msg'] = e.get_full_details()
            return Response(ret_data)

        ret_data['tag_list'] = tag_list
        return Response(ret_data)

    def all(self,classify):
        """获取所有问题/用户标签"""
        if classify == 0:
            tag_list = TagToUser.objects.all()
            serializers = TagToUserModelSerializer(instance=tag_list,many=True)
            return serializers.data
        elif classify == 1:
            tag_list = TagToQuestion.objects.all()
            print(tag_list)
            serializers = TagToQuestionModelSerializer(instance=tag_list,many=True)
            return serializers.data
        else:
            raise APIException(detail='classify 无效',code=204)


class QuestionModelAPIView(APIView):
    """问题列表/发布/删除视图"""

    authentication_classes = [jwtQueryParamsBaseAuthentication]

    def post(self,request):
        ret_data = {
            'status':200,
            'msg':'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])
        # 判断前台资源是否传递,如果没有,返回错误信息
        if not 'question_detail' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = '问题内容资源未传递'
            return Response(ret_data)

        # 获取资源信息
        question_detail = request.data['question_detail']
        # 关联发布问题的用户
        question_detail['we_chat_user'] = user.id
        serializer = QuestionModelCreateSerializer(data=question_detail)
        if serializer.is_valid():
            question = serializer.save()

            ret_data['question_id'] = question.id
            return Response(ret_data)
        else:
            print(serializer.errors)
            ret_data['status'] = 203
            ret_data['msg'] = '后台资源未就位'

        return Response(ret_data)

    def delete(self,request):
        ret_data = {
            'status':200,
            'msg':'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])

        # 判断前台资源是否传递,如果没有,返回错误信息
        if not 'question_id' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = 'question_id未传递'
            return Response(ret_data)

        # 获取问题id
        question_id = request.data['question_id']
        # 判断是否存在该id的问题,如果没有,返回错误信息
        if not Question.objects.filter(id=question_id,we_chat_user=user).first():
            ret_data['status'] = 206
            ret_data['msg'] = '错误question_id'
            return Response(ret_data)

        # 获取问题主体
        question_obj = Question.objects.get(id=question_id,we_chat_user=user)
        attachs = ImageForQuestion.objects.filter(question=question_obj)
        # 先删除问题的附件
        for item in attachs:
            item.delete()

        # 再删除问题
        question_obj.delete()

        return Response(ret_data)


class QuestionDetailModelAPIView(APIView):
    """问题详情视图"""

    authentication_classes = [jwtQueryParamsBaseAuthentication]

    def get_obj(self,id):
        """获取问题的详情"""
        try:
            obj = Question.objects.filter(id=id).first()
        except :
            raise Http404

        serializer = QuestionModelSerializer(instance=obj)

        return serializer.data

    def get_answer(self,id):
        """获取问题的相关答复"""
        obj = Answer.objects.filter(question_id=id,grandpa=None)
        if not obj:
            return None
        serializer = AnswerModelSerializer(instance=obj,many=True)
        return serializer.data

    def get(self,request):
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])

        # 判断前台资源是否传递,如果没有,返回错误信息
        if not 'question_id' in request.query_params:
            ret_data['status'] = 204
            ret_data['msg'] = 'question_id未传递'
            return Response(ret_data)


        # 获取信息资源
        question_id = request.query_params['question_id']

        ret_data['question_detail'] = self.get_obj(id=question_id)
        ret_data['answer_list'] = self.get_answer(id=question_id)
        # print(ret_data)
        return Response(ret_data)


class UserInfoModelAPIView(APIView):
    """
        get: 浏览用户信息:基本信息, 个性标签, 院校信息
        发布过的问题,回答的答复

        put: 修改用户信息
    """

    authentication_classes = [jwtQueryParamsBaseAuthentication]

    def get(self,request):
        ret_data = {
            'status':200,
            'msg':'ok'
        }
        # 判断前台资源是否传递,如果没有,返回错误信息
        if not 'we_chat_user_id' in request.query_params:
            ret_data['status'] = 204
            ret_data['msg'] = 'we_chat_user_id未传递'
            return Response(ret_data)

        # 获取资源
        we_chat_user_id = request.query_params['we_chat_user_id']

        # 判断是否存在该用户,如果不存在, 返回警告信息
        if not WeChatUser.objects.filter(id=we_chat_user_id).first():
            ret_data['status'] = 206
            ret_data['msg'] = '无效的用户'
            return Response(ret_data)

        # 获取用户
        user = WeChatUser.objects.get(id=we_chat_user_id)
        user_serializer = WeChatUserInfoModelSerializer(instance=user)

        # 获取用户的问题
        user_questions = Question.objects.filter(we_chat_user=user)
        question_serializer = QuestionModelSerializer(instance=user_questions,many=True)

        # 获取用户的问题
        user_answer = Answer.objects.filter(we_chat_user=user)
        answer_serializer = AnswerModelSerializer(instance=user_answer,many=True)

        ret_data['userInfo'] = user_serializer.data
        ret_data['question_list'] = question_serializer.data
        ret_data['answer_list'] = answer_serializer.data

        return Response(ret_data)

    def put(self,request):
        ret_data = {
            'status':200,
            'msg':'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])

        # 判断前台是否传递信息, 如果没有,,返回错误信息
        if not 'modify' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = 'modify资源未传递'
            return Response(ret_data)

        # 获取资源
        modify = request.data['modify']
        # 获取要修改的字段与值
        field = modify['field']
        value = modify['value']

        if field == 'wanna'.strip():
            user.wanna = value.strip()
        elif field == 'declaration'.strip():
            user.declaration = value.strip()
        else:
            ret_data['status'] = '203'
            ret_data['msg'] = '不是正确该被修改的信息'
            return Response(ret_data)
        user.save()
        seralizer = WeChatUserInfoModelSerializer(instance=user)
        ret_data['we_chat_user'] = seralizer.data
        return Response(ret_data)


class AnswerModelAPIView(APIView):
    """答复视图"""

    authentication_classes = [jwtQueryParamsBaseAuthentication]

    def get(self,request):
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])
        if not "question_id" in request.query_params:
            ret_data['status'] = 204
            ret_data['msg'] = 'question_id资源未传递'
            return Response(ret_data)

        question_id = request.query_params['question_id']

        # 查询回复列表
        answers = Answer.objects.filter(question_id=question_id, grandpa=None)

        # 反序列化
        serializer = AnswerModelSerializer(instance=answers,many=True)

        ret_data['answer_list'] = serializer.data
        # print(serializer.data)
        return Response(ret_data)

    def post(self,request):
        ret_data = {
            'status':200,
            'msg':'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])

        # 确定前台是否传递信息资源,如果没有,返回错误信息
        if not 'answerResourceful' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = 'answerResourceful资源未传递'
            return Response(ret_data)

        # 获取资源
        answerResourceful = request.data['answerResourceful']
        answerResourceful['we_chat_user'] = user.id
        # 反序列化
        serializer = AnswerCreateModelSerializer(data=answerResourceful)
        # 校验数据有效性
        if serializer.is_valid():
            # print(serializer.validated_data)
            #数据保存
            answer = serializer.save()
            '''同时建立回复关系'''
            question = Question.objects.get(id=answerResourceful['question'])

            replyRelationship = {
                'replier':user.id,
                'answer':answer.id,
                'recipient':question.we_chat_user.id,
                'question':question.id
            }
            # 反序列化
            relation_serializer = ReplyRelationshipModelSerializer(data=replyRelationship)
            # 数据校验
            if relation_serializer.is_valid():
                # 数据入库
                relation_serializer.save()
            else:
                print(relation_serializer.errors)
                ret_data['msg'] = '回复关系处理异常'
            ret_data['answer'] = serializer.data


            '''建立用户与该问题下的标签的回复关系'''
            tag_list = TagToQuestion.objects.filter(question=question)
            for item in tag_list:
                BindUserAndQuestionTag.objects.get_or_create(user=user,tag=item)

            return Response(ret_data)
        else:
            print(serializer.errors)
            ret_data['status'] = 203
            ret_data['msg'] = '数据校验失败,请重试'
            return Response(ret_data)

    def delete(self,request):
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])

        # 判断前台资源是否传递,如果没有,返回错误信息
        if not 'answer_id' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = 'answer_id未传递'
            return Response(ret_data)

        # 获取问题id
        answer_id = request.data['answer_id']
        # 判断是否存在该id的问题,如果没有,返回错误信息
        if not Answer.objects.filter(id=answer_id, we_chat_user=user).first():
            ret_data['status'] = 206
            ret_data['msg'] = '错误answer_id'
            return Response(ret_data)

        # 获取回复主体
        answer_obj = Answer.objects.get(id=answer_id, we_chat_user=user)
        attachs = ImageForAnswer.objects.filter(answer=answer_obj)
        # 先删除问题的附件
        for item in attachs:
            item.delete()

        # 再删除问题
        answer_obj.delete()

        return Response(ret_data)

    def put(self,request):
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])

        # 判断前台资源是否传递,如果没有,返回错误信息
        if not 'answer_id' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = 'answer_id未传递'
            return Response(ret_data)

        # 获取问题id
        answer_id = request.data['answer_id']
        # 判断是否存在该id的问题,如果没有,返回错误信息
        if not Answer.objects.filter(id=answer_id, we_chat_user=user).first():
            ret_data['status'] = 206
            ret_data['msg'] = '错误answer_id'
            return Response(ret_data)

        # 获取回复主体
        answer_obj = Answer.objects.get(id=answer_id, we_chat_user=user)

        answer_obj.optimum = True
        answer_obj.save()
        return Response(ret_data)


class SlideshowModelAPIView(APIView):
    """轮播图视图"""
    # authentication_classes = [jwtQueryParamsBaseAuthentication]

    def get(self,request):
        ret_data = {
            'status': 200,
            'msg':'ok'
        }

        # 获取后台轮播图数据
        slideshow = Slideshow.objects.all()
        len = slideshow.count()
        if len > 5:
            slideshow = slideshow[len-5:len]
        # 序列化
        serializer = SlideshowModelSerializer(instance=slideshow,many=True)

        ret_data['slideshow'] = serializer.data
        return Response(ret_data)


class FeedbackModelAPIView(APIView):
    """反馈视图"""

    authentication_classes = [jwtQueryParamsBaseAuthentication]

    def post(self,request):
        ret_data = {
            'status': 200,
            'msg':'ok'
        }

        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])

        # 判断前台是否传递信息资源, 如果没有,返回错误信息
        if not 'content' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = 'content资源未传递'
            return Response(ret_data)

        # 获取信息资源
        content = request.data['content']
        data = {
            'content':content,
            'user':user.id
        }
        # 反序列化
        serializer = FeedbackModelSerializer(data=data)
        # 校验数据
        if serializer.is_valid():
            # 保存数据
            feedback = serializer.save()
            print(feedback)
            ret_data['msg'] = '感谢您的反馈, 我们一定会认真考虑您的意见!'
            return Response(ret_data)
        else:
            ret_data['status'] = 203
            ret_data['msg'] = '数据校验失败,请重试'
        return Response(ret_data)


class InviteRelationshipModelAPIView(APIView):
    """受邀关系视图"""

    authentication_classes = [jwtQueryParamsBaseAuthentication]

    def get(self,request):
        """用于罗列用户的受邀信息"""
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        user = WeChatUser.objects.get(openID=request.user['openID'])
        invitee_list = InviteRelationship.objects.filter(invitee=user)
        serializer = InviteRelationshipListModelSerializer(instance=invitee_list,many=True)
        ret_data['invitee_list'] = serializer.data
        return Response(ret_data)

    def put(self,request):
        """用于更改受邀关系的accpet属性,即用户在前台阅览了该信息,表示以接受到
            设值为true,否则一直表示该信息一直未被用户查阅,以该属性提示用户
        """
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])
        # 判断前台是否传递资源信息,如果没有,返回错误信息
        if not 'id' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = 'id没有传递'
            return Response(ret_data)
        # 获取信息资源
        id = request.data['id']
        # 如果id 取值为'all',则更改该用户全部的受邀记录的accpet属性
        if not id == 'ALL':
            # 获取inviteRelationship对象
            if not InviteRelationship.objects.filter(id=id, invitee=user):
                ret_data['status'] = 203
                ret_data['msg'] = '不是正确的邀请关系id,请勿违规操作'
                return Response(ret_data)
            inviteRelationship = InviteRelationship.objects.get(id=id, invitee=user)
            # 修改接受属性
            inviteRelationship.accpet = True
            inviteRelationship.save()
        else:
            list = InviteRelationship.objects.filter(invitee=user)
            list.update(accpet=True)
        return Response(ret_data)

    def post(self,request):
        """用于建立用户受邀关系的视图"""
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])

        # 判断前台是否传递资源信息,如果没有,返回错误信息
        if not 'resourceful' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = 'resourceful没有传递'
            return Response(ret_data)
        # 获取资源信息
        resourceful = request.data['resourceful']
        resourceful['sponsor'] = user.id
        # 反序列化
        serializer = InviteRelationshipModelSerializer(data=resourceful)

        if serializer.is_valid():
            serializer.save()
            return Response(ret_data)
        else:
            print(serializer.errors)
            ret_data['status'] = 203
            ret_data['msg'] = '不是正确的数据信息,请勿违规操作'
            return Response(ret_data)

    def delete(self,request):
        """用于删除单个/多个受邀关系的视图"""
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])
        # 判断前台是否传递资源信息,如果没有,返回错误信息
        if not 'id' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = 'id没有传递'
            return Response(ret_data)
        # 获取信息资源
        id = request.data['id']

        # 如果id 取值为'all',则删除该用户全部的受邀记录
        if not id == 'ALL':
            # 判断是否存在该对象性
            if not InviteRelationship.objects.filter(id=id, invitee=user):
                ret_data['status'] = 203
                ret_data['msg'] = '不是正确的邀请关系id,请勿违规操作'
                return Response(ret_data)

            # 获取inviteRelationship对象
            inviteRelationship = InviteRelationship.objects.get(id=id, invitee=user)
            # 修改接受属性
            inviteRelationship.delete()
        else:
            InviteRelationship.objects.filter(invitee=user).delete()

        return Response(ret_data)


class ReplyRelationshipModelAPIView(APIView):
    """回复关系视图"""

    authentication_classes = [jwtQueryParamsBaseAuthentication]

    def get(self,request):
        """用于罗列用户的回复关系信息"""
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])
        # 获取该用户回复关系列表
        reply_list = ReplyRelationship.objects.filter(recipient=user)
        serializer = ReplyRelationshipListModelSerializer(instance=reply_list,many=True)

        ret_data['reply_list'] = serializer.data
        return Response(ret_data)

    def put(self,request):
        """修改用户某条记录的接受状态"""
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])
        # 判断前台是否传递资源信息,如果没有,返回错误信息
        if not 'id' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = 'id没有传递'
            return Response(ret_data)
        # 获取信息资源
        id = request.data['id']
        # 如果id 取值为'all',则更改该用户全部的受邀记录的accpet属性
        if not id == 'ALL':
            # 获取ReplyRelationship对象
            if not ReplyRelationship.objects.filter(id=id, recipient=user):
                ret_data['status'] = 203
                ret_data['msg'] = '不是正确的邀请关系id,请勿违规操作'
                return Response(ret_data)
            replyRelationship = ReplyRelationship.objects.get(id=id, recipient=user)
            # 修改接受属性
            replyRelationship.accpet = True
            replyRelationship.save()
        else:
            list = ReplyRelationship.objects.filter(recipient=user)
            list.update(accpet=True)

        return Response(ret_data)

    def delete(self,request):
        """用于删除单个/多个受邀关系的视图"""
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])
        # 判断前台是否传递资源信息,如果没有,返回错误信息
        if not 'id' in request.data:
            ret_data['status'] = 204
            ret_data['msg'] = 'id没有传递'
            return Response(ret_data)
        # 获取信息资源
        id = request.data['id']

        # 如果id 取值为'all',则删除该用户全部的受邀记录
        if not  id == 'ALL':
            # 判断是否存在该对象性
            if not ReplyRelationship.objects.filter(id=id, recipient=user):
                ret_data['status'] = 203
                ret_data['msg'] = '不是正确的邀请关系id,请勿违规操作'
                return Response(ret_data)

            # 获取inviteRelationship对象
            replyRelationship = ReplyRelationship.objects.get(id=id, recipient=user)
            # 修改接受属性
            replyRelationship.delete()
        else:
            ReplyRelationship.objects.filter(recipient=user).delete()

        return Response(ret_data)


class InviteModelAPIView(APIView):
    authentication_classes = [jwtQueryParamsBaseAuthentication]

    def get(self,request):
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])
        # 判断前台是否传递资源信息,如果没有,返回错误信息
        if not 'question_id' in request.query_params:
            ret_data['status'] = 204
            ret_data['msg'] = 'question_id没有传递'
            return Response(ret_data)
        # 获取资源
        question_id = request.query_params['question_id']
        if not Question.objects.filter(id=question_id):
            ret_data['status'] = 203
            ret_data['msg'] = '错误的id'
            return Response(ret_data)

        # 获取主体
        question = Question.objects.get(id=question_id)
        # 获取问题下的tag
        tag_list = TagToQuestion.objects.filter(question=question)
        user_for_tag_cont = {}
        tag_for_user = {}
        # 循环找出每个tag的回复用户, 并将每个用户的出现次数赋初值
        for item in tag_list:
            users = BindUserAndQuestionTag.objects.filter(tag=item)
            tag_for_user[item.text] = users
            for u in users:
                user_for_tag_cont[u] = 0
        # 循环计数每个标签下对应的用户出现次数
        for item in tag_for_user.items():
            if item[1] != None:
                for user in item[1]:
                    user_for_tag_cont[user] += 1
        sorted(user_for_tag_cont.items(), key=lambda item: item[1], reverse=True)

        user_for_tag = user_for_tag_cont.keys()
        if len(user_for_tag) > 10:
            user_for_tag = user_for_tag[0:9]

        # 循环获得最多十个的用户
        users = []
        for item in user_for_tag:
            users.append(item.user)

        users_serializer = WeChatUserBriefModelSerializer(instance=users, many=True)
        ret_data['be_invited'] = users_serializer.data
        return Response(ret_data)


class SearchQuestionModelAPIView(APIView):
    """问题搜索视图"""
    authentication_classes = [jwtQueryParamsBaseAuthentication]

    def get(self,request):
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])
        # 判断前台是否传递资源信息,如果没有,返回错误信息
        if not 'question_title' in request.query_params:
            ret_data['status'] = 204
            ret_data['msg'] = 'question_title没有传递'
            return Response(ret_data)

        question_title = request.query_params['question_title']

        if question_title == '':
            ret_data['status'] = 204
            ret_data['msg'] = 'question_title为空'
            return Response(ret_data)
        questiones = Question.objects.filter(title__regex=question_title)
        if not questiones:
            ret_data['status'] = 206
            ret_data['msg'] = '没有搜索到哦!'
            return Response(ret_data)

        serializer = SearchQuestionModelSerializer(instance=questiones,many=True)
        ret_data['question_list'] = serializer.data
        return Response(ret_data)


class QuestionListModelAPIView(APIView):
    """首页列表"""
    def get(self,request):
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        query_set = Question.objects.all()
        # 创建分页对象
        page = PageNumberPagination()
        # 在数据库中获取分页的数据
        page_list = page.paginate_queryset(queryset=query_set, request=request, view=self)
        # 对分页进行序列化
        serializer = QuestionModelSerializer(instance=page_list,many=True)
        ret_data['count'] = len(page_list)
        ret_data['nextPage'] = page.get_next_link()
        ret_data['previousPage'] = page.get_previous_link()
        ret_data['question_list'] = serializer.data
        return Response(ret_data)


class AnswerChildrenModelAPIView(APIView):
    """获取/创建子评论视图"""
    authentication_classes = [jwtQueryParamsBaseAuthentication]

    def get(self,request):
        ret_data = {
            'status': 200,
            'msg': 'ok'
        }
        # 获取用户对象
        user = WeChatUser.objects.get(openID=request.user['openID'])

        if not 'answer_id' in request.query_params and not 'question_id' in request.query_params:
            ret_data['status'] = 204
            ret_data['msg'] = 'answer_id或question_id没有传递'
            return Response(ret_data)

        answer_id = request.query_params['answer_id']
        question_id = request.query_params['question_id']

        answer_list= Answer.objects.filter(question_id=question_id, grandpa=answer_id)
        answer_serializer = AnswerModelSerializer(instance=answer_list, many=True)
        ret_data['answer_children_list'] = answer_serializer.data
        return Response(ret_data)
